package com.example.demolib.service;

import com.example.demolib.entity.BookInfo;
import com.example.demolib.entity.PageRequest;
import com.example.demolib.entity.UserInfo;
import com.example.demolib.mapper.BookInfoMapper;
import com.example.demolib.mapper.UserInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
@Slf4j
@Service
public class BookService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private BookInfoMapper bookInfoMapper;

    public List<UserInfo> queryUserInfo() {
        log.info("queryUserInfo:{}", userInfoMapper.queryUserInfo());
        return userInfoMapper.queryUserInfo();
    }

    public Integer addBook(BookInfo bookInfo) {
        log.info("addBook:{}", bookInfo);
        return  bookInfoMapper.addBook(bookInfo);
    }

    /**
     *      实现status与statusCN之间的映射
     *      此方法可以用枚举类代替
     * @param bookInfo
     */
    private void statusMapStatusCN(BookInfo bookInfo) {
        if(bookInfo.getStatus()==1){
            bookInfo.setStatusCN("可借阅");
        } else if (bookInfo.getStatus()==2) {
            bookInfo.setStatusCN("不可借阅");
        }
        return;
    }

    public PageRequest<BookInfo> getListByPage(Integer currentPage,Integer pageSize) {
        log.info("getListByPage:{},{}",currentPage,pageSize);
        // 传递offset和limit
        Integer limit = pageSize;
        Integer offset = (currentPage - 1) * limit;
        // 操作数据库
        List<BookInfo> list = bookInfoMapper.getListByPage(offset,limit);
        Integer count = bookInfoMapper.count();
        for (BookInfo bookInfo : list) {
            // 实现status与statusCN之间的映射
            statusMapStatusCN(bookInfo);
        }
        // 返回PageRequest对象
        return new PageRequest<BookInfo>(list,count,currentPage,pageSize);
//        PageRequest<BookInfo> pageRequest = new PageRequest<>();
//        pageRequest.setRecords(list);
//        pageRequest.setCount(count);
//        pageRequest.setCurrentPage(currentPage);
//        pageRequest.setPageSize(pageSize);
//        return pageRequest;
    }

    public BookInfo selectBookById(Integer bookId) {
        return bookInfoMapper.selectBookById(bookId);
    }

    public Integer updateBook(BookInfo bookInfo) {
        return bookInfoMapper.updateBook(bookInfo);
    }

    public Integer deleteBookById(Integer bookId) {
        BookInfo bookInfo = new BookInfo();
        bookInfo.setId(bookId);
        // 使用逻辑删除，status为0表示数据已删除
        bookInfo.setStatus(0);
        return bookInfoMapper.updateBook(bookInfo);
    }

    public Integer batchDeleteBookById(List<Integer> ids) {
        return bookInfoMapper.batchDeleteBookById(ids);
    }
}
